<template>
  <div class="update-avatar">
    <img :src="photo" ref="image" />

    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import { uploadPhoto } from '@/api'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
export default {
  // data() {
  //   return {
  //     myCropper: null,
  //     afterImg: ''
  //   }
  // },
  props: {
    photo: {
      type: String,
      required: true
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.myCropper = new Cropper(this.$refs.image, {
        viewMode: 1,
        dragMode: 'none',
        initialAspectRatio: 1,
        aspectRatio: 1,
        preview: '.before',
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false
      })
    },
    async onConfirm() {
      const canvas = this.myCropper.getCroppedCanvas()
      // console.log(canvas)
      // canvas.toBlob((file)=>{
      //   console.log(file);

      // })
      const file = await new Promise((resolve) => {
        canvas.toBlob((file) => {
          resolve(file)
        })
      })
      // console.log(file)

      // sureSava() {
      //   this.afterImg = this.myCropper
      //     .getCroppedCanvas({
      //       imageSmoothingQuality: 'high'
      //     })
      //     .toDataURL('image/jpeg')
      // }
      try {
        this.$toast.loading({
          message: '上传头像中...',
          forbidClick: true
        })
        const { data } = await uploadPhoto(file)
        // console.log(data)
        this.$emit('updata-photo', data.data.phpto)
        this.$toast.success('上传图片成功')
      } catch (error) {
        this.$toast.fail('上传图片成功')
      }
    }
  }
}
</script>

<style scoped lang="less">
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 65%;
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    z-index: 9999;
  }
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
